﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Text;

namespace XmlToPdf
{
    /// <summary>
    /// 利用xslt把普通xml转换为iTextSharp能够利用的格式
    /// </summary>
    public class FormatXml
    {
        public static void FormatXmlFile()
        {
            try
            {
                //
                XPathDocument inputSource = new XPathDocument("../salary.xml");
                //
                XslTransform xslt = new XslTransform();
                //
                xslt.Load("../formatXml.xsl");
                //
                XmlTextWriter myWriter = new XmlTextWriter("result.xml", null);
                //
                xslt.Transform(inputSource, null, myWriter);
                //
                myWriter.Close();
            }
            catch (Exception e)
            {

            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="reader">由string构造的XmlReader对象，包含xml数据</param>
        /// <param name="filePath">文件路径</param>
        /// <param name="resultXmlName">文件名</param>
        /// <param name="salaryDate">当前年月</param>
        public static void FormatXmlReader(XmlReader reader, string filePath, string resultXmlName,string salaryDate)
        {            
                //利用XmlReader创建XPathDocument对象
                XPathDocument inputSource = new XPathDocument(reader);
                //生成XslTransform转换器
                XslTransform xslt = new XslTransform();
                //加载xslt文件
                xslt.Load(filePath + "formatXml.xsl");
                //构建样式表参数列表
                XsltArgumentList arguments = new XsltArgumentList();
                //添加参数year
                arguments.AddParam("year", "", salaryDate.Substring(0,4));
                //添加参数month
                arguments.AddParam("month", "", salaryDate.Substring(4));
                //
                XmlTextWriter myWriter = new XmlTextWriter(filePath + resultXmlName + ".xml", Encoding.UTF8);
                //转换
                xslt.Transform(inputSource, arguments, myWriter);
                //
                myWriter.Close();            
            
        }
        
    }
}
